package DigitalSignature;

import NumTheory.NumTheory;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RSA_Sign {

    private static final MessageDigest SHA1;

    private final NumTheory numTheory = new NumTheory();

    static {
        try {
            SHA1 = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public BigInteger sign(BigInteger d, BigInteger n, byte[] plaintext) {
        byte[] digestInit = SHA1.digest(plaintext);
        byte[] digest = new byte[digestInit.length + 1];
        digest[0] = 0x00;
        System.arraycopy(digestInit, 0, digest, 1, digestInit.length);
        BigInteger plaintextNum = new BigInteger(digest);
        return numTheory.fastPow(plaintextNum, d, n);
    }

    public boolean verify(BigInteger e, BigInteger n, BigInteger signature, byte[] plaintext) {
        BigInteger verify = numTheory.fastPow(signature, e, n);
        byte[] digestInit = SHA1.digest(plaintext);
        byte[] digest = new byte[digestInit.length + 1];
        digest[0] = 0x00;
        System.arraycopy(digestInit, 0, digest, 1, digestInit.length);
        BigInteger plaintextNum = new BigInteger(digest);
        return verify.equals(plaintextNum);
    }

}
